package com.cskaoyan.market.service;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.util.MybatisUtils;
import com.cskaoyan.market.vo.FormVo;
import com.cskaoyan.market.vo.UserCountIncreaseVo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdminStatServiceImpl implements AdminStatService {

    @Override
    public FormVo user() {
        SqlSession userSession = MybatisUtils.getSession();
        FormVo formVo = new FormVo();
        List<UserCountIncreaseVo> list=new ArrayList<>();
        MarketUserMapper marketUserMapper = userSession.getMapper(MarketUserMapper.class);
        MarketUserExample marketUserExample = new MarketUserExample();
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
        HashMap<String, Integer> stringIntegerMap = groupByData(marketUsers);
        for (Map.Entry<String, Integer> Entry : stringIntegerMap.entrySet()) {
            list.add(new UserCountIncreaseVo(Entry.getKey(), Entry.getValue()));
        }
        formVo.setRows(list);
        return formVo;
    }

    private HashMap<String, Integer> groupByData(List<MarketUser> marketUsers) {
        HashMap<String, Integer> userCountMap = new HashMap<>();
        for (MarketUser marketUser : marketUsers) {
            String addTime = marketUser.getAddTime().toLocalDate().toString();
            Integer userCount = userCountMap.getOrDefault(addTime, 0);
            userCountMap.put(addTime, userCount+1);
        }
        return userCountMap;
    }
}
